package com.xinyue.auto.reader.process;

import java.util.List;

import org.dom4j.Element;

import com.xinyue.auto.bean.Attribute;
import com.xinyue.auto.bean.Query;
import com.xinyue.auto.exception.JoinException;
import com.xinyue.auto.reader.Process;
import com.xinyue.auto.reader.major.JoinMajor;
import com.xinyue.auto.reader.util.SetterUtil;
import com.xinyue.auto.util.StringUtil;

public class JoinProcess extends JoinMajor{
	public JoinProcess(Process read) {
		super(read);
	}
	private String manyName;//many-many名称
	
	private Attribute one;//属性数据封装对象
	private String one_en;//one的实体对象
	private Attribute two;//属性数据封装对象
	private String two_en;//one的实体对象

	@SuppressWarnings("unchecked")
	@Override
	protected void validate() throws Exception {
		manyName = xml.attributeValue(name_);
		
		List<Element> joins = xml.elements(join_);
		
		if(joins == null || joins.size() != 2) {
			throw new JoinException("必须定义join标签且只能定义2个", holder.getException());
		}
		
		//join one
		commonRead(joins.get(0));
		one = att;
		one_en = entity;
		
		//join two
		commonRead(joins.get(1));
		two = att;
		two_en = entity;
		
		querys.add(queryMethod(one, two_en, two.getName()));
		querys.add(queryMethod(two, one_en, one.getName()));
		querys.add(deleteMethod(one));
		querys.add(deleteMethod(two));
		
		holder.getDaoImpt().add(holder.getBasePkg() + ".bean." + one_en);
		holder.getDaoImpt().add(holder.getBasePkg() + ".bean." + two_en);
		
		atts.add(one);
		atts.add(two);
	}

	@Override
	protected void install() {
		//将此属性添加至Entity对象中
		holder.getEntity().getAtts().addAll(atts);
		holder.getEntity().getFinds().addAll(querys);
	}
	
	/**
	 * 查询方法
	 * @return
	 */
	private Query queryMethod(Attribute query, String eName, String by) {
		Query q = new Query();
		
		q.setMethod("query" + eName + "By" + StringUtil.firstUpper(query.getName()));
		q.setReturnType("List<" + eName + ">");
		q.setParams(query.getType() + " " + query.getName());
		q.setState("select o from " + manyName + " a," + eName + " o where o." + by + "=a." + by + " and a." + query.getName() + "=:" + query.getName());
		
		String[] setter = {SetterUtil.setterHQL(query.getName(), query.getType())};
		q.setParamSetter(setter);
		q.setWarning(true);
		
		return q;
	}
	
	/**
	 * 删除方法
	 * @return
	 */
	private Query deleteMethod(Attribute att) {
		Query q = new Query();
		
		q.setReturnType("Integer");
		q.setMethod("deleteBy" + StringUtil.firstUpper(att.getName()));
		q.setState("delete " + manyName + " where " + att.getName() + "=?");
		q.setParams(att.getType() + " " + att.getName());
		
		String[] setter = {SetterUtil.setterHQL(att.getName(), att.getType())};
		q.setParamSetter(setter);
		
		q.setOnly(true);
		q.setConvert(true);
		q.setQuery(false);
		
		return q;
	}
}